import React from 'react';
import moment from 'moment';
import {browserHistory,Link} from 'react-router';
import { Form, Button, Input, Select, message,Modal, TimePicker,Icon } from 'antd';
import $ from 'jquery';
import config from '../../../config/config';
const allRouter=config.router;
const FormItem = Form.Item;
const token = sessionStorage.getItem('token');
const Option = Select.Option;
let uuid = 0;
let descCount=0;
class addSchedule extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            paths:this.props.location,
            rolesOptions: [],
            type: this.props.params.id,
            hasNamed:false,//验证重名
        }
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {
        //为了防止增加后立马编辑而uuid没有清0
        uuid = 0;
        if(this.props.params.scheduleId != "0"){
            let url=allRouter.patientOrigin+'/sheduling/one/'+this.props.params.scheduleId;
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    console.log(data);
                    if(data.code==200){
                        let values=data.source;
                        let count = values.workingtime.length;
                        for (let i = 1; i<count;i++){
                            this.add();
                        }
                    }else{
                        console.log("获取排班列表出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        }
    }
    componentDidMount() {
        if(this.props.params.scheduleId != "0"){
            let url=allRouter.patientOrigin+'/sheduling/one/'+this.props.params.scheduleId;
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    console.log(data);
                    if(data.code==200){
                        let values=data.source;
                        let myObject={};
                        values.workingtime.map((item,i)=>{
                            console.log(i);
                            console.log(item);
                            if(i>0){
                                let time1='timePicker2'+(i-1);
                                let time2='timePicker1'+(i-1);
                                console.log(time2);
                                console.log(time1);
                                myObject[time2]=moment(item.starttime,'HH:mm:ss');
                                myObject[time1]=moment(item.endtime,'HH:mm:ss');
                            }
                        })
                        this.props.form.setFieldsValue({
                            name:values.name,
                            state:values.state,
                            timePicker1:moment(values.workingtime[0].starttime,'HH:mm:ss'),
                            timePicker2:moment(values.workingtime[0].endtime,'HH:mm:ss'),
                        });
                        console.log(myObject);
                        this.props.form.setFieldsValue(myObject);
                    }else{
                        console.log("获取患者来源名称出错");
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        }
    }
    //保存排班
    saveData(){
        this.props.form.validateFields((err,fieldsValue)=> {
            if (err) {
                return;
            }
            if(this.state.hasNamed){
                message.error('该班次名称已经存在!',1);
                return;
            }
            let isBefore=false;
            if( fieldsValue['timePicker2'].isBefore(fieldsValue['timePicker1'])){
                isBefore=true;
            }
            const values = {
                ...fieldsValue,
                'timePicker1': fieldsValue['timePicker1'].format('HH:mm:00'),
                'timePicker2': fieldsValue['timePicker2'].format('HH:mm:00'),
            };
            console.log(values);
            let timeData = [];
            timeData.push({starttime:values.timePicker1,endtime:values.timePicker2})
                values.keys.map(i=>{
                    let time1='timePicker2'+i;
                    let time2='timePicker1'+i;
                    while(fieldsValue[time2]&&fieldsValue[time1]){
                        values[time2]=fieldsValue[time2].format('HH:mm:00');
                        values[time1]=fieldsValue[time1].format('HH:mm:00');
                        if(fieldsValue[time1].isBefore(fieldsValue[time2])){
                            isBefore=true;
                        }
                        timeData.push({starttime:values[time2],endtime:values[time1]});
                        if(fieldsValue[time2]&&fieldsValue[time1]){
                            break;
                        }
                    }
                });
            console.log(values);
            console.log(timeData);
            //结束时间小于开始时间
            if(isBefore){
                message.error('班次开始时间不能大于结束时间',1);
                return;
            }
            if(this.props.params.scheduleId != "0"){
                Modal.confirm({
                    title: '修改排班信息',
                    className:'confirm-error',
                    content: '操作提醒！修改成功之后排班管理、分诊也会更改。',
                    onCancel: () => { },
                    onOk: () => {
                        let url=allRouter.patientOrigin+'/sheduling/update';
                        $.ajax({
                            url: url,
                            type: "post",
                            async: true,
                            traditional: true,
                            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                            data: {
                                name:values.name,
                                state:values.state,
                                workingtime:JSON.stringify(timeData),
                                id:this.props.params.scheduleId
                            },
                            success:data => {
                                console.log(data);
                                if(data.code===200){
                                    message.info('排班修改成功',);
                                    browserHistory.push('scheduleSetting');
                                }else{
                                    message.info('排班修改失败');
                                }
                            },
                            error:err=>{
                                console.log(err);
                            }
                        });
                    }
                });

            }else{
                let url=allRouter.patientOrigin+'/sheduling/save';
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    traditional: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data: {
                        name:values.name,
                        state:values.state,
                        workingtime:JSON.stringify(timeData)
                    },
                    success:data => {
                        console.log(data);
                        if(data.code===200){
                            message.info('排班增加成功',);
                            browserHistory.push('scheduleSetting');
                        }else if(data.code===201){
                            message.error('排班名称已存在，请修改',1);
                        }else{
                            message.info('排班增加失败',1);
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回科室列表页面吗？',
            onCancel:()=>{console.log('取消')},
            onOk:()=>{
                browserHistory.push('scheduleSetting');
            }
        })
    }
    //移除班次
    remove (k)  {
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        if (keys.length === 0) {
            return;
        }
        descCount++;
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    }
    //增加班次
    add  ()  {
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat(uuid);
        console.log(nextKeys);
        uuid++;
        form.setFieldsValue({
            keys: nextKeys,
        });
    }
    // 验证名称是否重复
    hadnamed(e){
        console.log(e.target.value);
        let scheduleName = e.target.value
        let url=allRouter.patientOrigin+'/sheduling/hadnamed';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                name:e.target.value
            },
            success:data => {
                console.log(data);
                if(data.code===200){
                    this.setState({
                        hasNamed:false,
                    })
                }else {
                    this.props.form.setFields({
                        name: { value: scheduleName,errors: [new Error(data.mes)] }
                    });
                    this.setState({
                        hasNamed:true,
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });
    }
    render() {
        const { getFieldDecorator,getFieldValue } = this.props.form;
        const config = {
            rules: [{ type: 'object', required: true, message: '请选择时间' }],
        };
        //班次时间模板
        const formItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 18 } };
        getFieldDecorator('keys', { initialValue: [] });
        const keys = getFieldValue('keys');
        const formItems = keys.map((k, index) => {
            return (
                <div className="storeRow" key={k}>
                    <FormItem  style={{ display: 'inline-block', width: '20%' }}
                               {...{ labelCol: { span: 10 }, wrapperCol: { span: 12 } }}
                               label="班次时间："
                    >
                        {getFieldDecorator('timePicker1'+k, config)(
                            <TimePicker minuteStep={30}  format="HH:mm:00" placeholder="开始时间"/>
                        )}
                    </FormItem>
                    _____&nbsp;
                    <FormItem  style={{ display: 'inline-block', width: '50%' }}
                               {...{ labelCol: { span: 2 }, wrapperCol: { span: 18 } }}
                    >
                        {getFieldDecorator('timePicker2'+k,config)(
                            <TimePicker width={500} minuteStep={30} format="HH:mm:00" placeholder="结束时间"/>
                        )}
                    </FormItem>
                    {keys.length > 0 ? (
                        <div style={{ display: 'inline-block', float:'right',marginRight:'17%' }}>
                            <Button onClick={() => this.remove(k)} type="primary">
                                <Icon type="minus" />
                            </Button>
                        </div>
                    ) : null}
                </div>
            );
        });
        return (
            <div className='container'>
                <div className='add-department-box'>
                    <div className="show-template">
                        <span>*{this.props.params.scheduleId != "0"?"编辑":"新增"}排班</span>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="班次名称" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('name', {
                                rules: [
                                    { required: true, message: '班次名称不能为空' },
                                    { max: 10, message: '班次名称不能超过10个字' },
                                    { pattern: /^([\u4e00-\u9fa5])+$/, message: '请输入中文' }
                                    ],
                            })(
                                <Input placeholder="请输入班次名称" onKeyUp={this.hadnamed.bind(this)} />
                            )}
                        </FormItem>
                    </div>
                    <div className='storeRow my-clear-fix'>
                        <FormItem style={{ display: 'inline-block', width: '20%' }}
                                  {...{ labelCol: { span: 10 }, wrapperCol: { span: 12 } }}
                                  label="班次时间："
                        >
                            {getFieldDecorator('timePicker1', config)(
                                <TimePicker minuteStep={30} format="HH:mm:00" placeholder="开始时间"/>
                            )}
                        </FormItem>
                        _____&nbsp;
                        <FormItem style={{ display: 'inline-block', width: '50%' }}
                                  {...{ labelCol: { span: 2 }, wrapperCol: { span: 18 } }}
                        >
                            {getFieldDecorator('timePicker2',config)(
                                <TimePicker minuteStep={30} format="HH:mm:00" placeholder="结束时间" width={500}/>
                            )}
                        </FormItem>
                        <div style={{ display: 'inline-block', float:'right',marginRight:'17%' }}>
                            <Button  onClick={this.add.bind(this)} type="primary">
                                <Icon type="plus" />
                            </Button>
                        </div>
                    </div>
                    {formItems}
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="状态" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('state', {
                                initialValue: "启用",
                                rules: [{ required: true, message: '状态属性不能为空' }],

                            })(
                                <Select style={{ width: '100% '}}>
                                    <Option value="启用">启用</Option>
                                    <Option value="禁用">禁用</Option>
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>
                </div>
            </div>
        )
    }
}
const addScheduleForm = Form.create()(addSchedule);
export default addScheduleForm;